<?php
namespace app\controller\admin;

use app\BaseController;
use think\facade\Request;
use app\model\PrinterModel;
use app\model\OrderModel;

/**
 * 小票打印机管理控制器
 */
class Printer extends BaseController
{
    /**
     * 获取打印机列表
     */
    public function index()
    {
        $list = PrinterModel::get_list();
        return json([
            'status' => 0,
            'list' => $list
        ]);
    }

    /**
     * 获取打印机详情
     */
    public function info()
    {
        $printer_id = Request::param('id');
        $info = PrinterModel::get_info($printer_id);
        
        return json([
            'status' => 0,
            'data' => $info
        ]);
    }

    /**
     * 添加打印机
     */
    public function add()
    {
        $data = [
            'name' => Request::param('name'),
            'type' => Request::param('type', 'feie'), // feie: 飞鹅打印机, yilianyun: 易联云
            'printer_sn' => Request::param('printer_sn'),
            'printer_key' => Request::param('printer_key'),
            'api_url' => Request::param('api_url', ''),
            'status' => Request::param('status', 1),
            'is_default' => Request::param('is_default', 0)
        ];

        // 验证必填项
        if (empty($data['name']) || empty($data['printer_sn'])) {
            return json([
                'status' => 1,
                'description' => '打印机名称和设备号不能为空'
            ]);
        }

        $printer_id = PrinterModel::add2($data);
        
        // 如果设置为默认,更新其他打印机
        if ($data['is_default'] == 1) {
            PrinterModel::set_default($printer_id);
        }

        return json([
            'status' => 0,
            'description' => '添加成功',
            'printer_id' => $printer_id
        ]);
    }

    /**
     * 更新打印机
     */
    public function edit()
    {
        $printer_id = Request::param('id');
        $data = [
            'name' => Request::param('name'),
            'type' => Request::param('type'),
            'printer_sn' => Request::param('printer_sn'),
            'printer_key' => Request::param('printer_key'),
            'api_url' => Request::param('api_url', ''),
            'status' => Request::param('status', 1),
            'is_default' => Request::param('is_default', 0)
        ];

        PrinterModel::update2($printer_id, $data);
        
        // 如果设置为默认,更新其他打印机
        if ($data['is_default'] == 1) {
            PrinterModel::set_default($printer_id);
        }

        return json([
            'status' => 0,
            'description' => '更新成功'
        ]);
    }

    /**
     * 删除打印机
     */
    public function delete()
    {
        $printer_id = Request::param('id');
        PrinterModel::delete2($printer_id);

        return json([
            'status' => 0,
            'description' => '删除成功'
        ]);
    }

    /**
     * 设置默认打印机
     */
    public function set_default()
    {
        $printer_id = Request::param('id');
        PrinterModel::set_default($printer_id);

        return json([
            'status' => 0,
            'description' => '设置成功'
        ]);
    }

    /**
     * 打印订单小票
     */
    public function print_order()
    {
        $order_id = Request::param('order_id');
        $printer_id = Request::param('printer_id', 0);

        // 获取订单信息
        $order = OrderModel::get_order($order_id);
        if (empty($order)) {
            return json([
                'status' => 1,
                'description' => '订单不存在'
            ]);
        }

        // 获取打印机
        if ($printer_id > 0) {
            $printer = PrinterModel::get_info($printer_id);
        } else {
            $printer = PrinterModel::get_default();
        }

        if (empty($printer)) {
            return json([
                'status' => 1,
                'description' => '未配置打印机'
            ]);
        }

        // 生成打印内容
        $print_content = $this->generate_receipt($order);

        // 调用打印接口
        $result = $this->send_to_printer($printer, $print_content);

        // 记录打印日志
        PrinterModel::add_log([
            'printer_id' => $printer['id'],
            'order_id' => $order_id,
            'print_content' => $print_content,
            'print_result' => json_encode($result)
        ]);

        if ($result['status'] == 0) {
            return json([
                'status' => 0,
                'description' => '打印成功'
            ]);
        } else {
            return json([
                'status' => 1,
                'description' => '打印失败: ' . $result['message']
            ]);
        }
    }

    /**
     * 生成小票内容
     */
    private function generate_receipt($order)
    {
        $content = "<CB>神秘商城</CB><BR>";
        $content .= "<CB>订单小票</CB><BR>";
        $content .= "--------------------------------<BR>";
        $content .= "订单号: " . $order['order_no'] . "<BR>";
        $content .= "下单时间: " . $order['create_time'] . "<BR>";
        $content .= "--------------------------------<BR>";
        
        // 商品信息
        foreach ($order['goods'] as $goods) {
            $content .= $goods['goods_name'];
            if (!empty($goods['goods_option'])) {
                $content .= "(" . $goods['goods_option'] . ")";
            }
            $content .= "<BR>";
            $content .= "  单价:¥" . number_format($goods['goods_price'], 2) . " ";
            $content .= "数量:x" . $goods['goods_num'] . " ";
            $content .= "小计:¥" . number_format($goods['goods_total'], 2) . "<BR>";
        }
        
        $content .= "--------------------------------<BR>";
        
        // 费用明细
        foreach ($order['total'] as $total_item) {
            $content .= $total_item['code_text'] . ": ¥" . number_format($total_item['value'], 2) . "<BR>";
        }
        
        $content .= "--------------------------------<BR>";
        
        // 收货信息
        if ($order['shipping_method'] == 'package') {
            $content .= "收货人: " . $order['address_name'] . "<BR>";
            $content .= "电话: " . $order['address_phone'] . "<BR>";
            $content .= "地址: " . $order['address_province'] . $order['address_city'] . $order['address_area'] . $order['address_detail'] . "<BR>";
        } else if ($order['shipping_method'] == 'pickup') {
            $content .= "<CB>自提订单</CB><BR>";
            if (!empty($order['pickup'])) {
                $content .= "自提点: " . $order['pickup'][0]['store_name'] . "<BR>";
            }
        }
        
        if (!empty($order['message'])) {
            $content .= "备注: " . $order['message'] . "<BR>";
        }
        
        $content .= "--------------------------------<BR>";
        $content .= "<CB>感谢您的惠顾!</CB><BR>";
        $content .= "<CB>欢迎再次光临!</CB><BR>";
        $content .= "<QR>www.x-mii.com</QR>"; // 二维码

        return $content;
    }

    /**
     * 发送到打印机
     */
    private function send_to_printer($printer, $content)
    {
        if ($printer['type'] == 'feie') {
            return $this->print_feie($printer, $content);
        } else if ($printer['type'] == 'yilianyun') {
            return $this->print_yilianyun($printer, $content);
        } else {
            return [
                'status' => 1,
                'message' => '不支持的打印机类型'
            ];
        }
    }

    /**
     * 飞鹅打印机接口
     */
    private function print_feie($printer, $content)
    {
        $user = ''; // 飞鹅账号
        $ukey = $printer['printer_key']; // 飞鹅UKEY
        $sn = $printer['printer_sn']; // 打印机编号
        $time = time();
        
        $sign = sha1($user . $ukey . $time);
        
        $data = [
            'user' => $user,
            'stime' => $time,
            'sig' => $sign,
            'apiname' => 'Open_printMsg',
            'sn' => $sn,
            'content' => $content,
            'times' => 1
        ];
        
        $api_url = !empty($printer['api_url']) ? $printer['api_url'] : 'http://api.feieyun.cn/Api/Open/';
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $result = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($result, true);
        
        if ($result['ret'] == 0) {
            return ['status' => 0, 'message' => '打印成功'];
        } else {
            return ['status' => 1, 'message' => $result['msg']];
        }
    }

    /**
     * 易联云打印机接口
     */
    private function print_yilianyun($printer, $content)
    {
        // 易联云打印接口实现
        // 具体实现根据易联云API文档
        return ['status' => 0, 'message' => '打印成功'];
    }

    /**
     * 获取打印记录
     */
    public function logs()
    {
        $order_id = Request::param('order_id', 0);
        $printer_id = Request::param('printer_id', 0);
        
        $logs = PrinterModel::get_logs($order_id, $printer_id);
        
        return json([
            'status' => 0,
            'list' => $logs
        ]);
    }
}
